<template>
  <div class="">
    <h1>{{id ? '编辑' : '新建'}}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <el-select v-model="model.parent" placeholder="请选择" clearable>
          <el-option
            v-for="item in parentsOptions"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">{{id ? '保存' : '新建'}}</el-button>
      </el-form-item>
    </el-form>
  </div>
  
</template>

<script>
import {putCategoryCreate, getCategoryEditDetail, putCategoryEdit, getCategoryList} from '@/api/category'
export default {
  name: "CategoryEdit",
  props: {
    id: {
      type: String
    }
  },
  data() {
    return {
      model: {},
      parentsOptions: []
    };
  },
  created() {
    this.getParents()
    this.id && this.getCategoryEditDetail()
  },
  methods: {
    async save() {
      let data = this.model
      if (this.id) {
        await putCategoryEdit(this.id,data) //编辑数据
      } else {
        await putCategoryCreate(data) //创建数据
      }
      this.$router.push('/categories/list')
      this.$message({
        type: 'success',
        message: this.id ? '编辑成功' : '创建成功'
      })
    },
    async getCategoryEditDetail() {
      let res = await getCategoryEditDetail(this.id)
      this.model = res.data
    },
    async getParents() {
      let params = {
        type: 'parent'
      }
      let res = await getCategoryList(params)
      this.parentsOptions = res.data.data
    }
  }
};
</script>

<style lang="less" scoped></style>
